package com.tracy.lifeproject.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.gc.flashview.FlashView;
import com.gc.flashview.listener.FlashViewListener;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.tracy.lifeproject.R;
import com.tracy.lifeproject.activity.DescriptionActivity;
import com.tracy.lifeproject.activity.DetailActivity;
import com.tracy.lifeproject.activity.LogInActivity;
import com.tracy.lifeproject.activity.SearchActivity;
import com.tracy.lifeproject.activity.SummerActivity;
import com.tracy.lifeproject.bean.BannerBean;
import com.tracy.lifeproject.bean.CustomPostsBean;
import com.tracy.lifeproject.bean.SecondBannerBean;
import com.tracy.lifeproject.constant.UrlString;
import com.tracy.lifeproject.utils.CommonAdapter;
import com.tracy.lifeproject.utils.MyHolder;
import com.tracy.lifeproject.utils.OKHttpUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 * <p>
 * 主页的碎片
 */
public class HomeFragment extends Fragment {
    @InjectView(R.id.fv_top)
    FlashView mFvTop;
    @InjectView(R.id.rv_secondbanner)
    RecyclerView mRvSecondbanner;
    @InjectView(R.id.rv_product)
    RecyclerView mRvProduct;
    @InjectView(R.id.rv_header)
    RecyclerViewHeader mRvHeader;
    @InjectView(R.id.srf_refresh)
    SwipeRefreshLayout mSrfRefresh;
    @InjectView(R.id.tb_top)
    Toolbar mTbTop;
    @InjectView(R.id.btn_search)
    ImageView mBtnSearch;
    private Activity mActivity;
    private final String TAG_BANNER = "banner";
    private final String TAG_SECONDBANNER = "secondbanner";
    private final String TAG_POSTS = "posts";
    private Handler mHandler = new Handler();
    private List<String> mBeanner;
    private List<String> mSecondBanner;
    private List<CustomPostsBean.DataBean.PostsBean> mPosts;
    private BannerBean mBannerBean;
    private String next_url = UrlString.URL_POSTS;
    private LinearLayoutManager mManager;
    private CommonAdapter mAdapter;

    public HomeFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        mTbTop.getBackground().setAlpha(0);
    }

    //初始化数据源
    private void initData() {
        mActivity = getActivity();
        mBeanner = new ArrayList<>();
        mSecondBanner = new ArrayList<>();
        mPosts = new ArrayList<>();

        mRvSecondbanner.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));

        mManager = new LinearLayoutManager(mActivity);
        mRvProduct.setLayoutManager(mManager);
        mRvHeader.attachTo(mRvProduct, true);
        mAdapter = new CommonAdapter(mActivity, mPosts, R.layout.bottom_rv_item) {
            @Override
            public void bindData(MyHolder holder, int position, Object bean) {
                ImageView iv_bigpic = holder.getViewById(R.id.iv_bigpic);
                Picasso.with(mActivity).load(mPosts.get(position).getCover_image_url()).into(iv_bigpic);
                holder.setText(mPosts.get(position).getLikes_count() + "", R.id.tv_like);

                initItemPostData(mPosts.get(position).getPost_items(), holder);

                postBigPicListener(iv_bigpic, position);
            }
        };
        mRvProduct.setAdapter(mAdapter);


        initBannerData();

        initSecondBannerData();

        initPostsData();

        initRvProductListener();

        mSrfRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mBeanner.size() == 0) {
                    initBannerData();
                }
                mSrfRefresh.setRefreshing(false);
            }
        });
    }

    private void initRvProductListener() {
        mRvProduct.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int lastPso = mManager.findLastVisibleItemPosition();
                int itemCount = mManager.getItemCount();
                if ((lastPso + 1 == itemCount) && newState == mRvProduct.SCROLL_STATE_IDLE) {
                    initPostsData();
                    Log.i("url", next_url);
                }
            }
        });
    }

    //解析顶部广告条的数据
    private void initBannerData() {
        OKHttpUtils.newInstance(mActivity).getAsyncMainData(UrlString.URL_BANNER, new OKHttpUtils.MyCallBack() {
            @Override
            public void onFailure(IOException e) {
                Toast.makeText(mActivity, "网络加载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String result) {
                mBannerBean = new Gson().fromJson(result, BannerBean.class);
                for (int i = 0; i < mBannerBean.getData().getBanners().size(); i++) {
                    mBeanner.add(mBannerBean.getData().getBanners().get(i).getImage_url());
                }
                mFvTop.setImageUris(mBeanner);
                flashViewListener();
                mSrfRefresh.setRefreshing(false);
            }
        }, TAG_BANNER);

    }

    //顶部轮播广告条的点击的监听
    private void flashViewListener() {

        mFvTop.setOnPageClickListener(new FlashViewListener() {
            @Override
            public void onClick(int position) {
                BannerBean.DataBean.BannersBean bannersBean = mBannerBean.getData().getBanners().get(position);
                switch (bannersBean.getType()) {
                    case "collection":
                        Intent intent = new Intent(mActivity, SummerActivity.class);
                        intent.putExtra("id", bannersBean.getTarget_id());
                        startActivity(intent);
                        break;
                    case "post":
                        Intent intent_web = new Intent(mActivity, DetailActivity.class);
                        intent_web.putExtra("id", bannersBean.getTarget_id());
                        startActivity(intent_web);
                        break;
                }
            }
        });
    }

    //加载第二部分广告条的图片
    private void initSecondBannerData() {
        OKHttpUtils.newInstance(mActivity).getAsyncMainData(UrlString.URL_SECONDBANNER, new OKHttpUtils.MyCallBack() {
            @Override
            public void onFailure(IOException e) {
                Toast.makeText(mActivity, "网络加载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String result) {
                final SecondBannerBean secondBannerBean = new Gson().fromJson(result, SecondBannerBean.class);
                for (int i = 0; i < secondBannerBean.getData().getSecondary_banners().size(); i++) {
                    mSecondBanner.add(secondBannerBean.getData().getSecondary_banners().get(i).getImage_url());
                }

                mRvSecondbanner.setAdapter(new CommonAdapter(mActivity, mSecondBanner, R.layout.secondbanner_rv_item) {
                    @Override
                    public void bindData(MyHolder holder, final int position, Object bean) {
                        ImageView iv_secondbanner = holder.getViewById(R.id.iv_secondbanner);
                        Picasso.with(mActivity).load(mSecondBanner.get(position)).into(iv_secondbanner);

                        secondBannerListener(position, iv_secondbanner, secondBannerBean);
                    }
                });
            }
        }, TAG_SECONDBANNER);

    }

    //第二个广告条的单张图片点击的监听
    private void secondBannerListener(final int position, ImageView iv_secondbanner, final SecondBannerBean secondBannerBean) {
        iv_secondbanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (secondBannerBean.getData().getSecondary_banners().get(position).getTarget_type()) {
                    case 0:
                        double targetId = (double) secondBannerBean.getData().getSecondary_banners().get(position).getTarget_id();
                        Intent intent_web = new Intent(mActivity, DetailActivity.class);
                        intent_web.putExtra("id", (int) targetId);
                        startActivity(intent_web);
                        break;
                    case 2:
                        double targetId_post = (double) secondBannerBean.getData().getSecondary_banners().get(position).getTarget_id();
                        Intent intent_post = new Intent(mActivity, SummerActivity.class);
                        intent_post.putExtra("id", (int) targetId_post);
                        startActivity(intent_post);
                        break;
                    default:
                        startActivity(new Intent(mActivity, LogInActivity.class));
                        break;
                }
            }
        });
    }

    //加载最下方list的数据
    private void initPostsData() {
        OKHttpUtils.newInstance(mActivity).getAsyncMainData(next_url, new OKHttpUtils.MyCallBack() {
            @Override
            public void onFailure(IOException e) {
                Toast.makeText(mActivity, "网络加载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String result) {
                CustomPostsBean CustomPostsBean = new Gson().fromJson(result, CustomPostsBean.class);
                next_url = CustomPostsBean.getData().getPaging().getNext_url();
                for (int i = 0; i < CustomPostsBean.getData().getPosts().size(); i++) {
                    mPosts.add(CustomPostsBean.getData().getPosts().get(i));
                }
                mAdapter.notifyDataSetChanged();
            }
        }, TAG_POSTS);
    }


    private void postBigPicListener(ImageView iv_bigpic, final int position) {
        iv_bigpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, DetailActivity.class);
                intent.putExtra("id", mPosts.get(position).getId());
                startActivity(intent);
            }
        });
    }

    //初始化每个POST单项的下面RecyclerView的数据
    private void initItemPostData(final List<CustomPostsBean.DataBean.PostsBean.PostItemsBean> postItemsBeanList, MyHolder holder) {
        RecyclerView rv_posts = holder.getViewById(R.id.rv_posts);
        rv_posts.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
        rv_posts.setAdapter(new CommonAdapter(mActivity, postItemsBeanList, R.layout.post_rv_item) {
            @Override
            public void bindData(MyHolder holder, int position, Object bean) {
                CustomPostsBean.DataBean.PostsBean.PostItemsBean postItemsBean = postItemsBeanList.get(position);
                ImageView iv_post = holder.getViewById(R.id.post_rv_pic);
                Picasso.with(mActivity).load(postItemsBean.getCover_image_url()).into(iv_post);
                holder.setText(postItemsBean.getName(), R.id.post_rv_title)
                        .setText("￥ " + postItemsBean.getPrice(), R.id.post_rv_price);

                postSmallPicListener(postItemsBean, iv_post);
            }
        });
    }

    private void postSmallPicListener(final CustomPostsBean.DataBean.PostsBean.PostItemsBean postItemsBean, ImageView iv_post) {
        iv_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, DescriptionActivity.class);
                intent.putExtra("id", postItemsBean.getId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        OKHttpUtils okHttpUtils = OKHttpUtils.newInstance(mActivity);
        okHttpUtils.cancel(TAG_BANNER);
        okHttpUtils.cancel(TAG_SECONDBANNER);
        okHttpUtils.cancel(TAG_POSTS);
    }

    @OnClick(R.id.btn_search)
    public void onClick() {
        startActivity(new Intent(mActivity, SearchActivity.class));
    }
}
